package com.zhrj.exam.common;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.io.Serializable;
import java.util.List;

/**
 * 统一响应结果封装类
 * @param <T> 响应数据类型
 */
public class Result<T> implements Serializable {
    private Integer code;    // 状态码
    private String msg;     // 消息
    private T data;         // 数据

    // ------------------------- 基础构造函数 -------------------------
    private Result(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    // ------------------------- 成功响应静态方法 -------------------------
    public static <T> Result<T> success() {
        return new Result<>(200, "操作成功", null);
    }

    public static <T> Result<T> success(T data) {
        return new Result<>(200, "操作成功", data);
    }

    public static <T> Result<T> success(String msg, T data) {
        return new Result<>(200, msg, data);
    }

    // ------------------------- 失败响应静态方法 -------------------------
    public static <T> Result<T> fail() {
        return new Result<>(400, "操作失败", null);
    }

    public static <T> Result<T> fail(String msg) {
        return new Result<>(400, msg, null);
    }

    public static <T> Result<T> fail(Integer code, String msg) {
        return new Result<>(code, msg, null);
    }

    // ------------------------- 链式调用方法 -------------------------
    public Result<T> code(Integer code) {
        this.code = code;
        return this;
    }

    public Result<T> msg(String msg) {
        this.msg = msg;
        return this;
    }

    public Result<T> data(T data) {
        this.data = data;
        return this;
    }

    // ------------------------- 常用状态码封装 -------------------------
    public static <T> Result<T> unAuthorized(String msg) {
        return new Result<>(401, msg, null);
    }

    public static <T> Result<T> forbidden(String msg) {
        return new Result<>(403, msg, null);
    }

    public static <T> Result<T> error(String msg) {
        return new Result<>(500, msg, null);
    }

    // ------------------------- Getter -------------------------
    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

    // ------------------------- 分页数据专用方法 -------------------------
    public static <T> Result<PageData<T>> pageSuccess(long total, List<T> list) {
        return Result.success(new PageData<>(total, list));
    }

    /**
     * 分页数据封装内部类
     */
    @Getter
    @AllArgsConstructor
    public static class PageData<T> {
        private final long total;
        private final List<T> list;
    }
}